﻿using System.ServiceModel.Channels;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.Phone.Shell;
using SMARTMobile.Common;
using SmartMobile.Data;
using SMARTMobile.Models;
using SMARTMobile.Framework;
using SMARTMobile.Models.Local;
using SMARTMobile.Models.Xml;
using SMARTMobile.Services.SMARTMobileServiceReference;
using SMARTMobile.Utilities;
using SMARTMobile.WinPhone;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Microsoft.Phone.Controls;
using SmartMobile.Data;
using System.IO;
using System.Data.Linq;
using SMARTMobile.Models.UI;
using System.Collections.ObjectModel;

namespace SMARTMobile.ViewModels
{
    public partial class MainViewModel : ViewModelBase
    {
        #region Application Bar

        private IApplicationBarMenuItem _menuItem1;
        private IApplicationBarMenuItem _menuItem2;
        private IApplicationBarMenuItem _menuItem3;

        #endregion

        private Grid _subMenu;
        private bool _wasSubMenuGridPrepared = false;
        ////private string _siteCode = "123";
        private bool _showSubMenu = false;
        private bool _newDevice;
        private int _checkBusy = 0;
        private bool _isNhanVien;
        private bool _isGiamSat;

        private ReloadDataSmartPhoneSoapClient _proxy;
        private readonly List<MenuModel> _menuList = new List<MenuModel>();
        private XmlSetting _setting;
        private bool _changeSetting;
        SmartMobileDBContext _smartMobileContext;
        private string _tenNhanVienTextBlock;
        private BitmapImage _avatarNhanVienImage;
        private string _siteNameDistributor;
        private string _addressDistributor;


        private Category _lion;
        private Category animals;
        private List<Category> _categoryList;
        public MainViewModel()
        {
            #region Commands

            this.LamTuyenCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteLamTuyenCommand
            };

            this.PhanTuyenCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecutePhanTuyenCommand
            };

            this.NhapThongTinKHCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteNhapThongTinKHCommand
            };

            this.ThietDatCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteThietDatCommand
            };

            this.DongBoThietBiCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteDongBoThietBiCommand
            };

            this.DongBoCuoiNgayCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteDongBoCuoiNgayCommand
            };

            this.QuyTrinhCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteQuyTrinhCommand
            };

            this.KhachHangCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteKhachHangCommand
            };

            this.TacVuCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteTacVuCommand
            };

            this.ChupHinhCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteChupHinhCommand
            };

            this.GheThamCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteGheThamCommand
            };

            this.BanDoCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteBanDoCommand
            };

            this.MainPageTapCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteMainPageTapCommand
            };

            #endregion

            this.CreateConnection();
        }

        public event EventHandler MessageBoxRequest;
        public event Action<object> SidebarStateChanged;
        private List<SmartMobile.Data.OBJECT> objects;
        private List<SmartMobile.Data.ObjectGroup> objectGroups;
        private List<SmartMobile.Data.GROUP> groups;
        private List<SmartMobile.Data.GROUPGROUP> groupGroups;
        private List<SmartMobile.Data.GroupMenu> groupMenus;
        private List<SmartMobile.Data.MENU> menus;
        private TreeModel _tree;

        #region Commands
        public ICommandRoute DongBoCuoiNgayCommand { get; private set; }

        public ICommandRoute GheThamCommand { get; private set; }
        public ICommandRoute BanDoCommand { get; private set; }
        public ICommandRoute QuyTrinhCommand { get; private set; }

        public ICommandRoute KhachHangCommand { get; private set; }

        public ICommandRoute TacVuCommand { get; private set; }

        public ICommandRoute ChupHinhCommand { get; private set; }

        public ICommandRoute DongBoThietBiCommand { get; private set; }
        public ICommandRoute ThietDatCommand { get; private set; }
        public ICommandRoute NhapThongTinKHCommand { get; private set; }
        public ICommandRoute HelpCommand { get; private set; }

        public ICommandRoute MainPageTapCommand { get; private set; }

        public ICommandRoute LamTuyenCommand { get; private set; }
        public ICommandRoute PhanTuyenCommand { get; private set; }

        #endregion

        #region Properties
        public TreeModel Tree
        {
            get { return this._tree; }
            set
            {
                this._tree = value;
                base.RaisePropertyChanged("Tree");
            }
        }
        public bool IsGiamSat
        {
            get { return this._isGiamSat; }
            set
            {
                this._isGiamSat = value;
                base.RaisePropertyChanged("IsGiamSat");
            }
        }

        public bool IsNhanVien
        {
            get { return this._isNhanVien; }
            set
            {
                this._isNhanVien = value;
                base.RaisePropertyChanged("IsNhanVien");
            }
        }

        public bool ShowSubMenu
        {
            get { return this._showSubMenu; }
            set
            {
                this._showSubMenu = value;
                base.RaisePropertyChanged("ShowSubMenu");
            }
        }

        public List<MenuModel> MenuList { get; private set; }

        public string TenNhanVienTextBlock
        {
            get { return _tenNhanVienTextBlock; }
            set { _tenNhanVienTextBlock = value; base.RaisePropertyChanged("TenNhanVienTextBlock"); }
        }

        public BitmapImage AvatarNhanVienImage
        {
            get { return _avatarNhanVienImage; }
            set { _avatarNhanVienImage = value; base.RaisePropertyChanged("AvatarNhanVienImage"); }
        }

        public string SiteNameDistributor
        {
            get { return _siteNameDistributor; }
            set { _siteNameDistributor = value; base.RaisePropertyChanged("SiteNameDistributor"); }
        }

        public string AddressDistributor
        {
            get { return _addressDistributor; }
            set { _addressDistributor = value; base.RaisePropertyChanged("AddressDistributor"); }
        }

        public List<Category> CategoryList
        {
            get { return _categoryList; }
            set
            {
                _categoryList = value;
                base.RaisePropertyChanged("CategoryList");
            }
        }

        public ReloadDataSmartPhoneSoapClient Proxy
        {
            get
            {
                if (_proxy == null && GlobalInformation.Endpoint != null)
                {
                    _proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);
                }

                return _proxy;

            }
            set { _proxy = value; }
        }

        #endregion

        #region ViewModelBase Overriden

        public override void Initialize(Uri uri)
        {
            //// Check sync data end date
            ////////this.CheckSyncDataEndDate();
            //// Check new device

            this.CheckNewDevice();

            // Load data from webservice when new device
            if (GlobalInformation.NewDevice)
            {
                ////ARSALESP salesp = this._smartMobileContext.ARSALESP.FirstOrDefault();

                ////if (salesp == null)
                ////{
                ////    base.IsBusy = true;
                ////    this.Proxy.GetArSaleSPAsync(this._siteCode);
                ////}
                ////else
                ////{
                MessageBox.Show("Vui lòng cài đặt thông tin người dùng");
                this.ThietDatCommand.RaiseCanExecuteChanged(true);
                base.PageNavigation.Navigate("ThietDat");
                ////}
            }
            else
            {
                if (_smartMobileContext.OBJECT.Any() && this._smartMobileContext.ARSALESPTYPE.Any())
                {
                    this.CreateMainViewButtons(this._smartMobileContext.ARSALESPTYPE.FirstOrDefault(), "QT");
                }

                // Lay tuan hien tai
                GlobalInformation.GetWeekOfMonth();

                if (GlobalInformation.ArSaleSPType.Usertype == "SS")
                {
                    this.IsNhanVien = false;
                    this.IsGiamSat = true;
                }
                else
                {
                    this.IsNhanVien = true;
                    this.IsGiamSat = false;
                }
            }
        }

        public override void ApplicationBarMenuClick(IApplicationBarMenuItem menuItem)
        {
            switch (menuItem.Text)
            {
                case "Đồng bộ dữ liệu":
                    base.PageNavigation.Navigate("DBDuLieu");
                    break;
                case "Thiết đặt":
                    base.PageNavigation.Navigate("ThietDat");
                    break;
            }
        }

        public override void PageLoaded(Uri uri)
        {
            var dauNgay = (from ars in _smartMobileContext.ARSALESPTYPE where ars.Workday == DateTime.Now.ToShortDateString() select ars).FirstOrDefault();
            if (dauNgay == null)
            {
                bool existData = false;
                foreach (var customer in this._smartMobileContext.TCARCUST)
                {
                    // Check mark of new customer
                    if (customer.Customerkey.Contains("_") || customer.IsEdit == "2")
                    {
                        existData = true;
                        break;
                    }
                }

                if (!GlobalInformation.NewDevice && existData)
                {
                    MessageBoxResult result = MessageBox.Show("Chưa đồng bộ dữ liệu bạn có muốn tiếp tục không?", "Cảnh báo", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.Cancel)
                    {
                        base.PageNavigation.Navigate("DongBoCuoiNgay");
                    }
                }

                var ar = this._smartMobileContext.ARSALESPTYPE.FirstOrDefault();
                if (ar != null)
                {
                    ar.Workday = DateTime.Now.ToShortDateString();
                    _smartMobileContext.SubmitChanges();

                    // Xoa ShopVistit
                    _smartMobileContext.Shopvisit.DeleteAllOnSubmit(_smartMobileContext.Shopvisit.ToList());
                    _smartMobileContext.SubmitChanges();

                    // Xoa IMAgecustomer, xoa hinh isolated
                    _smartMobileContext.IMAGECUSTOMER.DeleteAllOnSubmit(_smartMobileContext.IMAGECUSTOMER.ToList());
                    _smartMobileContext.SubmitChanges();

                    // Xoa hinh trong isolated
                    Utilities.ImageUtilities.DeleteAllImageFile();

                    // ApproveCustomer
                    _smartMobileContext.APPROVALCUSTOMERINFOR.DeleteAllOnSubmit(
                        _smartMobileContext.APPROVALCUSTOMERINFOR.ToList());
                    _smartMobileContext.SubmitChanges();

                    // Xoa het du lieu phan moi
                    ////PhonevendorVolume
                    _smartMobileContext.PhonevendorVolume.DeleteAllOnSubmit(
                        _smartMobileContext.PhonevendorVolume.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////PriceRangeContribution
                    _smartMobileContext.PriceRangeContribution.DeleteAllOnSubmit(
                        _smartMobileContext.PriceRangeContribution.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////OutletVendorContribution
                    _smartMobileContext.OutletVendorContribution.DeleteAllOnSubmit(
                        _smartMobileContext.OutletVendorContribution.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////Contact Infor
                    _smartMobileContext.OutletContact.DeleteAllOnSubmit(_smartMobileContext.OutletContact.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////CurrentOutDoorDisplay
                    _smartMobileContext.CurrentOutDoorDisplay.DeleteAllOnSubmit(
                        _smartMobileContext.CurrentOutDoorDisplay.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////CurrentInDoorDoorDisplay
                    _smartMobileContext.CurrentInDoorDoorDisplay.DeleteAllOnSubmit(
                        _smartMobileContext.CurrentInDoorDoorDisplay.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////OutletPGInformation
                    _smartMobileContext.OutetPGInformation.DeleteAllOnSubmit(
                        _smartMobileContext.OutetPGInformation.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////OutletNokiaPG
                    _smartMobileContext.OutletNokiaPG.DeleteAllOnSubmit(_smartMobileContext.OutletNokiaPG.ToList());
                    _smartMobileContext.SubmitChanges();
                    ////OutletNokiaMerchandisingPotential
                    _smartMobileContext.OutletNokiaMerchandisingPotential.DeleteAllOnSubmit(
                        _smartMobileContext.OutletNokiaMerchandisingPotential.ToList());
                    _smartMobileContext.SubmitChanges();
                }
            }

            //if (!string.IsNullOrEmpty(GlobalInformation.ConnectionStringWebService) && GlobalInformation.ConnectionStringWebService != "http:///ReloadDataSmartPhone.asmx")
            //{
            //    if (Proxy != null)
            //    {
            //        this.Proxy.GetArSaleSPCompleted += this.Proxy_GetArSaleSPCompleted;
            //        this.Proxy.GetDistributorCompleted += this.Proxy_GetDistributorCompleted;
            //        this.Proxy.GetSSCompleted += this.Proxy_GetSSCompleted;
            //    }
            //}

            if (GlobalInformation.ArSaleSPType != null)
            {
                this.TenNhanVienTextBlock = GlobalInformation.ArSaleSPType.Username;
                string fileName = ImageUtilities.CreateImageName();
                if (!string.IsNullOrEmpty(fileName))
                {
                    BitmapImage image = ImageUtilities.LoadImageFromIsolatedStorage(fileName);
                    if (image != null)
                    {
                        AvatarNhanVienImage = image;
                    }
                    else
                    {
                        AvatarNhanVienImage = new BitmapImage(new Uri("/Images/Customer.png", UriKind.Relative));
                    }
                }

                var distributor = (from dist in _smartMobileContext.Distributor where dist.SiteCode == GlobalInformation.ArSaleSPType.Sitecode select dist).FirstOrDefault();
                if (distributor != null)
                {
                    this.SiteNameDistributor = distributor.SiteName;
                    this.AddressDistributor = distributor.Address;
                }
            }
        }

        public override void PageUnloaded(Uri uri)
        {
            if (Proxy != null)
            {
                this.Proxy.GetArSaleSPCompleted -= this.Proxy_GetArSaleSPCompleted;
                this.Proxy.GetDistributorCompleted -= this.Proxy_GetDistributorCompleted;
                this.Proxy.GetSSCompleted -= this.Proxy_GetSSCompleted;
            }
        }

        #endregion

        #region Command Action Handlers

        private void ExecuteLamTuyenCommand(object commandParams)
        {
            this.LamTuyenCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("DuyetTTLamTuyen");
        }

        private void ExecutePhanTuyenCommand(object commandParams)
        {
            //this.HelpCommand.RaiseCanExecuteChanged(true);
            this.PhanTuyenCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("PhanTuyen");
        }

        private void ExecuteHelpCommand(object commandParams)
        {
            this.HelpCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("HoTro");
        }

        private void ExecuteThietDatCommand(object commandParams)
        {
            this.ThietDatCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("ThietDat");
        }

        private void ExecuteDongBoCuoiNgayCommand(object commandParams)
        {
            this.DongBoCuoiNgayCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("DongBoCuoiNgay");
        }

        private void ExecuteDongBoThietBiCommand(object commandParams)
        {
            if (GlobalInformation.ArSaleSPType != null)
            {
                this.DongBoThietBiCommand.RaiseCanExecuteChanged(true);
                base.PageNavigation.Navigate("NhanThongTin");
            }
            else
            {
                MessageBox.Show("Vui lòng cài đặt thông tin người dùng");
                this.DongBoThietBiCommand.RaiseCanExecuteChanged(true);
                base.PageNavigation.Navigate("ThietDat");
            }
        }

        private ARCUST GetArcustByID(Guid guid)
        {
            SmartMobileDBContext smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            return smartMobileContext.ARCUST.ToList().FirstOrDefault(x => x.ID_PK == guid);
        }

        private void ExecuteQuyTrinhCommand(object commandParams)
        {
            this.QuyTrinhCommand.RaiseCanExecuteChanged(true);
            if (GlobalInformation.ArSaleSPType.Usertype == "DSR")
            {
                this.CreateMainViewMenu("QT");
            }
            else
            {
                this.CreateMainViewMenu("SSQT");
            }

            this.OnSidebarStateChanged(commandParams);
        }

        private void ExecuteKhachHangCommand(object commandParams)
        {
            this.KhachHangCommand.RaiseCanExecuteChanged(true);
            this.CreateMainViewMenu("KH");

            //base.PageNavigation.Navigate("DSKhachHang");
            this.OnSidebarStateChanged(commandParams);
        }

        private void ExecuteNhapThongTinKHCommand(object commandParams)
        {
            this.NhapThongTinKHCommand.RaiseCanExecuteChanged(true);
            GlobalInformation.SelectedTCARCUS = null;
            base.PageNavigation.Navigate("CapNhatKhachHang");
        }

        private void ExecuteTacVuCommand(object commandParams)
        {
            this.TacVuCommand.RaiseCanExecuteChanged(true);
            if (GlobalInformation.ArSaleSPType.Usertype == "DSR")
            {
                this.CreateMainViewMenu("TV");
            }
            else
            {
                this.CreateMainViewMenu("SSHT");
            }

            this.OnSidebarStateChanged(commandParams);
        }

        private void ExecuteBanDoCommand(object obj)
        {
            this.BanDoCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("BanDo");
        }

        private void ExecuteGheThamCommand(object obj)
        {
            this.GheThamCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("GheTham");
        }

        private void ExecuteChupHinhCommand(object commandParams)
        {
            this.ChupHinhCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("ChupHinhMain");
        }

        private void ExecuteMainPageTapCommand(object commandParams)
        {
            this.OnSidebarStateChanged(commandParams);
        }

        #endregion

        #region Sub-Menu

        private void CreateSubMenu(int action)
        {
            // TODO: loop through the menu-item object from the web-service

            if (!_wasSubMenuGridPrepared)
            {
                // a row may contain maximum two squared buttons.
                RowDefinition firstRow = new RowDefinition();
                firstRow.Height = new GridLength(0, GridUnitType.Auto);

                RowDefinition marginRow = new RowDefinition();
                marginRow.Height = new GridLength(24);

                RowDefinition secondRow = new RowDefinition();
                secondRow.Height = new GridLength(0, GridUnitType.Auto);

                // adds first row to grid
                this._subMenu.RowDefinitions.Add(firstRow);
                this._subMenu.RowDefinitions.Add(marginRow);
                this._subMenu.RowDefinitions.Add(secondRow);

                // creates column definition for each squared button
                ColumnDefinition firstColumn = new ColumnDefinition();
                firstColumn.Width = new GridLength(0, GridUnitType.Auto);

                ColumnDefinition marginColumn = new ColumnDefinition();
                marginColumn.Width = new GridLength(24);

                ColumnDefinition secondColumn = new ColumnDefinition();
                secondColumn.Width = new GridLength(0, GridUnitType.Auto);

                // adds columns to grid
                this._subMenu.ColumnDefinitions.Add(firstColumn);
                this._subMenu.ColumnDefinitions.Add(marginColumn);
                this._subMenu.ColumnDefinitions.Add(secondColumn);

                this._wasSubMenuGridPrepared = true;
            }

            #region Creates Buttons

            // clears all buttons first.
            this._subMenu.Children.Clear();

            List<Button> buttons = new List<Button>();

            switch (action)
            {
                case 0:
                    // Quy trinh
                    buttons = this.CreateSquaredButtonList(
                        new ButtonInfo[] {
                            new ButtonInfo { ID = "00", Text = Localization.AppResources.COMMON_ACTION_ROUTE },
                            new ButtonInfo { ID = "01", Text = Localization.AppResources.COMMON_ACTION_HELP }
                        });
                    break;
                case 1:
                    // Khach hang
                    buttons = this.CreateSquaredButtonList(
                        new ButtonInfo[] {
                            new ButtonInfo { ID = "10", Text = Localization.AppResources.COMMON_ACTION_INPUTCUSTOMERINFO }
                        });
                    break;
                case 2:
                    // Tac vu
                    buttons = this.CreateSquaredButtonList(
                        new ButtonInfo[] {
                            new ButtonInfo { ID = "20", Text = Localization.AppResources.COMMON_ACTION_SETTING },
                            new ButtonInfo { ID = "21", Text = Localization.AppResources.COMMON_ACTION_DATASYNC }
                        });
                    break;
                default:
                    throw new ArgumentOutOfRangeException("Invalid actionID");
            }

            int i = 0, j = 0;

            foreach (Button button in buttons)
            {
                // set locations for button
                Grid.SetRow(button, j);
                Grid.SetColumn(button, i);

                // adds button to grid
                this._subMenu.Children.Add(button);

                if (i < 2)
                    i += 2;
                else
                {
                    i = 0;
                    j += 2;
                }

                // supports maximum 4 buttons
            }

            // adds back button
            Button backButton = this.CreateSquaredButton(new ButtonInfo { ID = "back", Text = Localization.AppResources.COMMON_ACTION_BACK });

            Grid.SetRow(backButton, j);
            Grid.SetColumn(backButton, i);

            // adds back-button to grid
            this._subMenu.Children.Add(backButton);

            #endregion
        }

        private List<Button> CreateSquaredButtonList(ButtonInfo[] buttonInfos)
        {
            List<Button> buttons = new List<Button>();
            foreach (ButtonInfo buttonInfo in buttonInfos)
            {
                buttons.Add(this.CreateSquaredButton(buttonInfo));
            }

            return buttons;
        }

        private Button CreateSquaredButton(ButtonInfo info)
        {
            StackPanel buttonStackPanel = new StackPanel();

            // button icon goes here
            Border buttonIcon = new Border
            {
                Height = 86,
                Width = 86,
                Background = new SolidColorBrush(Colors.Cyan)
            };

            // button text goes here
            TextBlock buttonText = new TextBlock
            {
                Text = info.Text,
                TextWrapping = TextWrapping.Wrap,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            buttonStackPanel.Children.Add(buttonIcon);
            buttonStackPanel.Children.Add(buttonText);

            Button button = new Button
            {
                Tag = info.ID,
                Content = buttonStackPanel,
                Style = (Style)Application.Current.Resources["TiltableButtonStyle"]
            };

            button.Click += this.SubMenuButton_Click;

            return button;
        }

        #endregion

        #region Web-service Event Handlers

        /// <summary>
        /// Get danh sach giam sat
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Proxy_GetSSCompleted(object sender, GetSSCompletedEventArgs e)
        {
            try
            {
                //Delete data before insert 
                _smartMobileContext.ARSS.DeleteAllOnSubmit(_smartMobileContext.ARSS.ToList());
                _smartMobileContext.SubmitChanges();

                // Add new data
                // serializes the XML data to Object
                List<XmlARSS> xmlSSList = XmlHelper.GetItems<XmlARSS>(e.Result.Nodes[1], "Table").ToList();

                ARSS ss = null;

                // converts to savable object-list
                foreach (XmlARSS item in xmlSSList)
                {
                    ss = new ARSS
                    {
                        ID_PK = Guid.NewGuid(),
                        SSCode = item.SScode,
                        SSName = item.SSName
                    };

                    _smartMobileContext.ARSS.InsertOnSubmit(ss);
                }

                _smartMobileContext.SubmitChanges();

                base.IsBusy = false;
                //if (this._checkBusy < 3)
                //{
                //    this._checkBusy += 1;
                //}
                //else
                //{
                //    this.IsBusy = false;
                //}
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// Get danh sach nhan vien 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Proxy_GetArSaleSPCompleted(object sender, GetArSaleSPCompletedEventArgs e)
        {
            try
            {
                // Delete data before insert 
                _smartMobileContext.ARSALESP.DeleteAllOnSubmit(_smartMobileContext.ARSALESP.ToList());
                _smartMobileContext.SubmitChanges();

                // Add new data               
                // serializes the XML data to Object
                List<XmlARSaleSP> saleList = XmlHelper.GetItems<XmlARSaleSP>(e.Result.Nodes[1], "Table").ToList();

                ARSALESP sale = null;

                // converts to savable object-list
                foreach (XmlARSaleSP item in saleList)
                {
                    sale = new ARSALESP
                    {
                        ID_PK = Guid.NewGuid(),
                        Salesp_key = item.Salesp_Key,
                        Salesp_name = item.Salesp_name,
                        Sitecode = item.SiteCode,
                        SScode = item.SSCode
                    };

                    _smartMobileContext.ARSALESP.InsertOnSubmit(sale);
                }

                _smartMobileContext.SubmitChanges();

                GlobalInformation.LoadNewData = true;

                this.Proxy.GetDistributorAsync(GlobalInformation.SiteCode);

                //if (this._checkBusy < 3)
                //{
                //    this._checkBusy += 1;
                //}
                //else
                //{
                //    this.IsBusy = false;
                //}
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// Get danh dach cong ty
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Proxy_GetDistributorCompleted(object sender, GetDistributorCompletedEventArgs e)
        {
            try
            {
                // Delete data before insert 
                _smartMobileContext.Distributor.DeleteAllOnSubmit(_smartMobileContext.Distributor.ToList());
                _smartMobileContext.SubmitChanges();

                // Add new data              
                List<XmlDistributor> distributorList = XmlHelper.GetItems<XmlDistributor>(e.Result.Nodes[1], "Table").ToList();

                Distributor localDistributor = null;

                // converts to savable object-list
                foreach (XmlDistributor distributor in distributorList)
                {
                    localDistributor = new Distributor
                    {
                        ID_PK = Guid.NewGuid(),
                        SiteCode = distributor.SiteCode,
                        SiteName = distributor.Name,
                        Address = distributor.Address
                    };

                    _smartMobileContext.Distributor.InsertOnSubmit(localDistributor);
                }
                _smartMobileContext.SubmitChanges();

                this.Proxy.GetSSAsync(GlobalInformation.SiteCode);

                //if (this._checkBusy < 3)
                //{
                //    this._checkBusy += 1;
                //}
                //else
                //{
                //    this.IsBusy = true;
                //}
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void Proxy_GetGroupMenuCompleted(object sender, GetGroupMenuCompletedEventArgs e)
        {
            ArrayOfXElement result = e.Result;

            List<XmlGroupMenu> menuGroupList = XmlHelper.GetItems<XmlGroupMenu>(e.Result.Nodes[1], "Table").ToList();
            string menudata = string.Empty;
            foreach (XmlGroupMenu xmlMenuGroup in menuGroupList)
            {
                menudata += xmlMenuGroup.GroupID + ", ";
                menudata += xmlMenuGroup.MenuID + "\n ";
            }
        }

        ////private void Proxy_GetMenuCompleted(object sender, GetMenuCompletedEventArgs e)
        ////{
        ////    ArrayOfXElement result = e.Result;

        ////    List<XmlMenu> menuList = XmlHelper.GetItems<XmlMenu>(e.Result.Nodes[1], "Table").ToList();
        ////    string listOfPersons = string.Join(",", menuList.Select(p => p.MenuID));
        ////    List<SqlMenu> sqlMenus = new List<SqlMenu>();
        ////    SqlMenu localSqlMenu = null;
        ////    string menudata = string.Empty;
        ////    // converts to savable object-list
        ////    foreach (XmlMenu xmlMenu in menuList)
        ////    {
        ////    //    localSqlMenu = new SqlMenu
        ////    //    {
        ////    //        MenuID = xmlMenu.MenuID,
        ////    //        MenuType = xmlMenu.MenuType,
        ////    //        MenuText = xmlMenu.MenuText,
        ////    //        IconFileName = xmlMenu.IconFileName,
        ////    //        MenuLevel = xmlMenu.MenuLevel,
        ////    //        UserType = xmlMenu.UserType,
        ////    //        IconCode = xmlMenu.IconCode,
        ////    };


        ////    //    ////menudata += xmlMenu.MenuID + ",";
        ////    //    ////menudata += xmlMenu.MenuType + ",";
        ////    //    ////menudata += xmlMenu.MenuText + ",";
        ////    //    ////menudata += xmlMenu.IconFileName + ",";
        ////    //    ////menudata += xmlMenu.MenuLevel + ",";
        ////    //    ////menudata += xmlMenu.UserType + ",";
        ////    //    ////menudata += xmlMenu.IconCode + "\n   ";

        ////    //    sqlMenus.Add(localSqlMenu);
        ////    //}

        ////    //// writes to local storage
        ////    //DataSourceService.Current.Write<List<SqlMenu>>("Menu", "MenuList", sqlMenus);
        ////}

        #endregion

        private void CreateConnection()
        {
            this._smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            this._smartMobileContext.CreateIfNotExists();
            this._smartMobileContext.LogDebug = true;
        }

        private void OnSidebarStateChanged(object sidebarUIObject)
        {
            if (this.SidebarStateChanged != null)
                this.SidebarStateChanged(sidebarUIObject);
        }

        private void SubMenuButton_Click(object sender, RoutedEventArgs e)
        {
            Button tapped = sender as Button;
            string tag = tapped.Tag.ToString();

            switch (tag)
            {
                case "00":
                    // Quy trinh lam tuyen
                    this.ShowSubMenu = false;
                    break;
                case "01":
                    // Yeu cau ho tro
                    this.ShowSubMenu = false;
                    break;
                case "10":
                    // Nhap thong tin khach hang
                    this.ShowSubMenu = false;
                    base.PageNavigation.Navigate("Distributor");
                    break;
                case "20":
                    // Thiet dat
                    this.ShowSubMenu = false;
                    break;
                case "21":
                    // Dong bo du lieu
                    this.ShowSubMenu = false;
                    break;
                default:
                    // Quay lai
                    this.ShowSubMenu = false;
                    break;
            }
        }

        private struct ButtonInfo
        {
            public string ID { get; set; }

            public string Text { get; set; }
        }

        private void CheckSyncDataEndDate()
        {
            // neu du lieu chua sync ve server yeu cau nguoi dung sync
            // sau khi sync xoa du lieu trong thiet bi
            this.DeleteData();

        }

        private void DeleteData()
        {

        }

        public void CheckNewDevice()
        {
            // It will copy from local to iso
            _smartMobileContext.CreateIfNotExists();

            // log sql query native on Output window
            _smartMobileContext.LogDebug = true;

            // Query - Same with SQL SERVER Linq
            ARSALESPTYPE sale = new ARSALESPTYPE();
            sale = _smartMobileContext.ARSALESPTYPE.FirstOrDefault();

            if (sale == null)
            {
                GlobalInformation.NewDevice = true;
            }
            else
            {
                GlobalInformation.ArSaleSPType = sale;
            }
        }

        private void GetAllInfoLocal()
        {
            //using (var db = this._connectionString.GetConnectionStringInfo())
            //{
            //    // Get setting
            //    // Get menu
            //    // ...
            //}
        }

        private void ReloadInfoFromWebService()
        {
            // Get menu
            // ...
        }

        // When click button "Dong bo du lieu"
        private void SyncDataBeginDate()
        {
            this.Proxy.GetCustTypeAsync(GlobalInformation.SiteCode, "typy=setting");
        }

        private void SyncDataEndDate()
        {

        }

        private void CreateTree()
        {
            _lion = new Category() { Name = "Lion" };

            animals = new Category()
            {
                Name = "Animals",
                SubCategories = new ObservableCollection<Category>()
                {
                    new Category()
                    {
                        Name = "Beast of preys", SubCategories = new ObservableCollection<Category>()
                        {
                            _lion,
                            new Category() { Name = "Tiger" },
                        }
                    },
                    new Category()
                    {
                        Name = "Herbivorous", SubCategories = new ObservableCollection<Category>()
                        {
                            new Category()
                            {
                                Name = "Rabbit",
                            },
                            new Category() { Name = "Cow" },
                        }
                    }
                },
                Icon = new BitmapImage(new Uri(@"/Images/Update.png", UriKind.RelativeOrAbsolute)),
                PrivateCommand = DongBoThietBiCommand
            };

            Tree = new TreeModel()
            {
                Categories = new ObservableCollection<Category>()
                {
                    animals,
                    new Category()
                    {
                        Name = "Automobile ", SubCategories = new ObservableCollection<Category>()
                        {
                            new Category()
                            {
                                Name = "Trucks", SubCategories = new ObservableCollection<Category>()
                                {
                                    new Category()
                                    {
                                        Name = "Volvo", SubCategories = new ObservableCollection<Category>()
                                        {
                                            new Category()
                                            {
                                                Name = "Volvo FH", SubCategories = new ObservableCollection<Category>()
                                                {
                                                }
                                            },
                                        }
                                    },
                                }
                            },
                            new Category()
                            {
                                Name = "Car", SubCategories = new ObservableCollection<Category>()
                                {
                                    new Category() { Name = "Audi R8" },
                                }
                            },
                        }
                    },
                }
            };
        }

        public void CreateMainViewButtons(ARSALESPTYPE arsalesptype, string objectID)
        {
            if (arsalesptype != null)
            {
                Tree = new TreeModel();
                this.CategoryList = new List<Category>();

                // Lay du lieu binding combobox
                this.objects = new List<OBJECT>(_smartMobileContext.OBJECT.Where(x => x.UseType == arsalesptype.Usertype && x.AppStatus == 0));
                this.objectGroups = new List<ObjectGroup>(_smartMobileContext.ObjectGroup.ToList());
                this.groups = new List<GROUP>(_smartMobileContext.GROUP.Where(x => x.AppStatus == 2).ToList());
                this.groupGroups = new List<GROUPGROUP>(_smartMobileContext.GROUPGROUP.ToList());
                this.groupMenus = new List<GroupMenu>(_smartMobileContext.GroupMenu.Where(x => x.Show == 1).ToList());
                this.menus = new List<MENU>(_smartMobileContext.MENU.ToList());

                foreach (var obj in objects)
                {
                    Category cat = new Category();
                    cat.Name = obj.Description;
                    cat.Icon = new BitmapImage(new Uri(GetImageSource(obj.Image), UriKind.RelativeOrAbsolute));
                    cat.PrivateCommand = GetCommand(obj.ID);
                    CategoryList.Add(cat);
                }

                if (arsalesptype.Usertype == "DSR")
                {
                    this.CreateMainViewMenu("QT");
                }
                else
                {
                    this.CreateMainViewMenu("SSQT");
                }
            }
        }

        public void CreateMainViewMenu(string objectID)
        {
            Tree.Categories.Clear();
            foreach (var objGroup in objectGroups.Where(x => x.Objectid == objectID))
            {
                foreach (var group in groups.Where(x => x.Groupkey == objGroup.GroupId))
                {
                    Category cat = new Category();
                    cat.Name = group.Groupdes;
                    cat.Icon = new BitmapImage(new Uri(GetImageSource(group.Image), UriKind.RelativeOrAbsolute));

                    List<string> groupGroupList =
                        groupGroups.Where(x => x.PrGroup == group.Groupkey).Select(x => x.ChGroup).ToList();
                    if (groupGroupList.Count == 0)
                    {
                        cat.PrivateCommand = GetCommand(group.Groupkey);
                    }

                    foreach (var ggroup in groups.Where(x => groupGroupList.Contains(x.Groupkey)).OrderBy(x => x.Sort))
                    {
                        Category gCategory = new Category();
                        gCategory.Name = ggroup.Groupdes;
                        gCategory.Icon =
                            new BitmapImage(new Uri(GetImageSource(string.Empty), UriKind.RelativeOrAbsolute));

                        var subMenus = groupMenus.Where(x => x.GroupKey == ggroup.Groupkey)
                            .OrderBy(x => x.Sort)
                            .ToList();
                        if (subMenus.Count > 0)
                        {
                            gCategory.SubCategories = new ObservableCollection<Category>();
                            foreach (var groupMenu in subMenus)
                            {
                                var menu = menus.FirstOrDefault(x => x.Type == groupMenu.MenuKey);
                                if (menu != null)
                                {
                                    Category subMenu = new Category();
                                    subMenu.Name = menu.Description;
                                    subMenu.Icon =
                                        new BitmapImage(new Uri(GetImageSource(menu.Imge),
                                            UriKind.RelativeOrAbsolute));
                                    subMenu.PrivateCommand = GetCommand(menu.Type);
                                    gCategory.SubCategories.Add(subMenu);
                                }
                            }
                        }
                        else
                        {
                            gCategory.PrivateCommand = GetCommand(group.Groupkey);
                        }

                        cat.SubCategories.Add(gCategory);
                    }

                    Tree.Categories.Add(cat);
                }
            }
        }

        //private ICommandRoute GetCommand(string key)
        //{
        //    switch (key)
        //    {
        //        case "DSRGT":
        //            {
        //                return GheThamCommand;
        //            }

        //        default:
        //            return null;
        //    }
        //}

        private string GetImageSource(string bindingSource)
        {
            switch (bindingSource)
            {
                case "saleorder.png":
                    {
                        return @"/Images/DauNgay.png";
                    }
                case "presale.png":
                    {
                        return @"/Images/TrenTuyen.png";
                    }
                case "report.png":
                    {
                        return @"/Images/CuoiNgay.png";
                    }
                case "changgps.png":
                    {
                        return @"/Images/BanDo.png";
                    }
                case "maps.png":
                    {
                        return @"/Images/BanDo.png";
                    }
                case "configuration.png":
                    {
                        return @"/Images/Setting.png";
                    }
                case "sumsale.png":
                    {
                        return @"/Images/Setting.png";
                    }
                case "changeroute.png":
                    {
                        return @"/Images/TrenTuyen.png";
                    }
                case "listcustomer.png":
                    {
                        return @"/Images/TrenTuyen.png";
                    }
                case "visit.png":
                    {
                        return @"/Images/GheTham.png";
                    }
                case "reload.png":
                    {
                        return @"/Images/DongBo.png";
                    }
                case "camera.png":
                    {
                        return @"/Images/ChupHinh.png";
                    }
                default:
                    return @"/Images/Setting.png";
            }
        }

        private ICommandRoute GetCommand(string key)
        {
            switch (key)
            {
                case "SSQT":
                case "QT":
                    {
                        return QuyTrinhCommand;
                    }
                case "KH":
                    {
                        return KhachHangCommand;
                    }
                case "SSHT":
                case "TV":
                    {
                        return TacVuCommand;
                    }

                case "SSGT":
                case "DSRGT":
                    {
                        return GheThamCommand;
                    }

                case "DSRDBDL":
                case "SSDBDL":
                    {
                        return DongBoThietBiCommand;
                    }
                case "TKHM":
                case "CNTTKH":
                    {
                        return NhapThongTinKHCommand;
                    }
                case "MAP":
                    {
                        return BanDoCommand;
                    }
                case "LTCHKH":
                case "BHCHKH":
                    {
                        return BanDoCommand;
                    }
                case "PTBH":
                    {
                        return PhanTuyenCommand;
                    }
                case "SSMAPCHR":
                    {
                        return LamTuyenCommand;
                    }
                case "ST":
                    {
                        return ThietDatCommand;
                    }
                case "SSST":
                    {
                        return ThietDatCommand;
                    }
                case "KHM":
                    {
                        return NhapThongTinKHCommand;
                    }
                case "SSDBDLCN":
                    {
                        return DongBoCuoiNgayCommand;
                    }
                case "DSRDBDLCN":
                    {
                        return DongBoCuoiNgayCommand;
                    }
                default:
                    return null;
            }
        }
    }
}
